package it.trekker.upload;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadBase;

public class UploadUtilities {

	public static List<String> receiveAndSaveFile(HttpServletRequest request, String path) {
		
		boolean isMultipart = FileUploadBase.isMultipartContent(request);
		List<String> files = new ArrayList<String>();
		
		if (isMultipart) {
			try {
				DiskFileUpload upload = new DiskFileUpload();
				List items = upload.parseRequest(request);
				Iterator itr = items.iterator();
				String filePath;
		
				// Ora controlliamo tutti gli item presenti
				// salvando tutti i file che sono stati inviati
				while (itr.hasNext()) {
					FileItem item = (FileItem) itr.next();
					if (!item.isFormField()) {
						File fullFile = new File(item.getName());
						File savedFile = new File(path, fullFile.getName());
						item.write(savedFile);
						filePath = savedFile.getAbsolutePath();
						files.add(filePath);
					}
				}
			} catch(Exception e) {
				System.err.println("Error: ");
				e.printStackTrace();
			}
		}
		
		return files;
	}
	
}
